package com.wythe.mall.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wythe.mall.R;
import com.wythe.mall.activity.AreaActivity;
import com.wythe.mall.activity.DeliveryStoreActivity;
import com.wythe.mall.activity.GoodsActivity;
import com.wythe.mall.activity.LoginActivity;
import com.wythe.mall.activity.MainActivity;
import com.wythe.mall.activity.RecommendActivity;
import com.wythe.mall.activity.SearchActivity;
import com.wythe.mall.activity.WebActivity;
import com.wythe.mall.adapter.DeliveryStoreAdapter;
import com.wythe.mall.adapter.HomeShopHListAdapter;
import com.wythe.mall.adapter.ImageShopAdapter;
import com.wythe.mall.adapter.MyFragmentPagerAdapter;
import com.wythe.mall.adapter.MyGridAdapter;
import com.wythe.mall.base.BaseActivity;
import com.wythe.mall.intf.OnRecyclerViewItemClickListener;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.model.BannerEntity;
import com.wythe.mall.model.ClassifyBean;
import com.wythe.mall.model.LabelBean;
import com.wythe.mall.model.ShopBean;
import com.wythe.mall.pay.Alipay;
import com.wythe.mall.pay.PayResult;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.Constants;
import com.wythe.mall.utils.DPIUtil;
import com.wythe.mall.utils.DensityUtils;
import com.wythe.mall.utils.GotoActivity;
import com.wythe.mall.utils.SharePreferenceUtils;
import com.wythe.mall.utils.UserManager;
import com.wythe.mall.view.CountDownTimerView;
import com.wythe.mall.view.MyItemDecoration;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.Transformer;

import okhttp3.Call;

import static android.app.Activity.RESULT_OK;


public class HomeFragment extends Fragment implements View.OnClickListener {
    public static final String TAG = BaseActivity.class.getSimpleName();
    private static final int SDK_PAY_FLAG = 1;

    private View view;
    private Banner banner, bannerActivity;
    private MyItemDecoration itemDecoration;
    private CountDownTimerView countDownTimerView;
    private RecyclerView mRlvShop;
    private HomeShopHListAdapter mAdapter;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private ArrayList<String> mTopTabTitle;
    private List<BannerEntity> tabList;
    private List<BannerEntity> entities;
    private List<String> mTablist;
    private List<String> mEntities;
    private ArrayList<Fragment> mFragments;
    private List<ShopBean> list;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private TextView mHomeTop;
    private RecyclerView mLabelShop;
    private MyGridAdapter adapter;
    private List<ClassifyBean> mClassList;
    private List<LabelBean> mLabelList;
    private int shopId;
    private RelativeLayout mRlup;
    private TextView mShopTitle;
    private String mTitle;
    private int screenWidth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        screenWidth = DensityUtils.screenWidth(getActivity());
        if (mFragments == null) {
            mFragments = new ArrayList<>();
        }
        mFragments.clear();
        if (mTopTabTitle == null) {
            mTopTabTitle = new ArrayList<>();
        }
        mTopTabTitle.clear();
        if (list == null) {
            list = new ArrayList<>();
        }
        list.clear();
        if (mClassList == null) {
            mClassList = new ArrayList<>();
        }
        mClassList.clear();
        if (tabList == null) {
            tabList = new ArrayList<>();
        }
        tabList.clear();
        if (entities == null) {
            entities = new ArrayList<>();
        }
        entities.clear();
        if (mTablist == null) {
            mTablist = new ArrayList<>();
        }
        mTablist.clear();
        if (mEntities == null) {
            mEntities = new ArrayList<>();
        }
        mEntities.clear();
        if (mLabelList == null) {
            mLabelList = new ArrayList<>();
        }
        mLabelList.clear();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        initView();

        return view;
    }

    private void initView() {
        view.findViewById(R.id.search_text).setOnClickListener(this);
        mHomeTop = view.findViewById(R.id.tv_top);
        mLabelShop = view.findViewById(R.id.rv_label);
        mRlup = view.findViewById(R.id.rl_up);
        mShopTitle = view.findViewById(R.id.tv_shop_day);
        RecyclerView.LayoutManager layoutManger = getGridManager();

        mLabelShop.setLayoutManager(layoutManger);

        //设置适配器

        //        MyAdapter adapter=new MyAdapter();

        //        recyclerView.setAdapter(adapter);

        adapter = new MyGridAdapter(getActivity(), mClassList);
        mLabelShop.setAdapter(adapter);
        adapter.setOnItemClickListener(new MyGridAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, ClassifyBean bean) {
                ((MainActivity) getActivity()).setmLabel(position);
                ((MainActivity) getActivity()).navigateTo(Constants.NAVIGATE_CATEGORY);
            }
        });

        mHomeTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoActivity.gotoActiviy(getActivity(),DeliveryStoreActivity.class);
            }
        });
        banner = (Banner) view.findViewById(R.id.home_banner);
        ViewGroup.LayoutParams layoutParams = banner.getLayoutParams();
        layoutParams.height = (screenWidth - DPIUtil.dip2px(getActivity(),30))/2;
        banner.setLayoutParams(layoutParams);
        mSwipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimary);
        mSwipeRefreshLayout.setRefreshing(true);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
                initLabel();
                getShopList(shopId);
            }
        });
        bannerActivity = (Banner) view.findViewById(R.id.home_activity_banner);
        mRlvShop = (RecyclerView) view.findViewById(R.id.rlv_shop);
        mAdapter = new HomeShopHListAdapter(getActivity(), list);
        mAdapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onRecyclerViewItemClick(View view, int position) {
                ShopBean shopBean = list.get(position);
                Bundle bundle = new Bundle();
                bundle.putInt("id", shopBean.getId());
                GotoActivity.gotoActiviy(getActivity(), GoodsActivity.class, bundle);
            }
        });
        mViewPager = (ViewPager) view.findViewById(R.id.home_shop_viewpager);
        mTabLayout = (TabLayout) view.findViewById(R.id.home_shop_tabLayout);

        //设置样式
        banner.setBannerStyle(Banner.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(Banner.CENTER);
        banner.setDelayTime(5000);//设置轮播间隔时间
        banner.isAutoPlay(true);
        banner.setOnBannerClickListener(new Banner.OnBannerClickListener() {//设置点击事件
            @Override
            public void OnBannerClick(View view, int position) {
                BannerEntity entity = tabList.get(position - 1);
                Bundle bundle = new Bundle();
                if (entity.getType() == 1) {
                    bundle.putInt("id", entity.getId());
                    bundle.putString("title", entity.getTitle());
                    GotoActivity.gotoActiviy(getActivity(), RecommendActivity.class, bundle);
                } else if (entity.getType() == 2) {
                    bundle.putString("url", entity.getWordKey());
                    GotoActivity.gotoActiviy(getActivity(), WebActivity.class, bundle);
                } else if (entity.getType() == 3) {
                    bundle.putInt("id", entity.getId());
                    GotoActivity.gotoActiviy(getActivity(), GoodsActivity.class, bundle);
                }
            }
        });
        //设置样式
        bannerActivity.setBannerStyle(Banner.CIRCLE_INDICATOR);
        bannerActivity.setIndicatorGravity(Banner.CENTER);
        bannerActivity.setDelayTime(5000);//设置轮播间隔时间
        bannerActivity.isAutoPlay(true);
        bannerActivity.setOnBannerClickListener(new Banner.OnBannerClickListener() {//设置点击事件
            @Override
            public void OnBannerClick(View view, int position) {
                BannerEntity entity = entities.get(position - 1);
                Bundle bundle = new Bundle();
                if (entity.getType() == 1) {
                    bundle.putInt("id", entity.getId());
                    bundle.putString("title", entity.getTitle());
                    GotoActivity.gotoActiviy(getActivity(), RecommendActivity.class, bundle);
                } else if (entity.getType() == 2) {
                    bundle.putString("url",entity.getWordKey());
                    GotoActivity.gotoActiviy(getActivity(),WebActivity.class,bundle);
                } else if (entity.getType() == 3) {
                    bundle.putInt("id", entity.getId());
                    GotoActivity.gotoActiviy(getActivity(), GoodsActivity.class, bundle);
                }
            }
        });

        mRlup.setOnClickListener(this);

        final LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRlvShop.setLayoutManager(manager);
        mRlvShop.setAdapter(mAdapter);
    }

    private RecyclerView.LayoutManager getGridManager() {

        //1.上下文

        //2.spanCout 列数

        return new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

    }

    private void initLabel() {
        JSONObject param = new JSONObject();

        ApiOkHttp.getClassifyShop(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                mClassList.clear();
                JSONArray array = null;
                try {
                    array = data.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        ClassifyBean bean = new Gson().fromJson(array.getJSONObject(i).toString(), ClassifyBean.class);
                        mClassList.add(bean);
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    private void initData() {
        JSONObject param = new JSONObject();
        ApiOkHttp.getBannerList(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                tabList.clear();
                entities.clear();
                mTablist.clear();
                mEntities.clear();
                try {
                    JSONObject dataJSONObject = data.getJSONObject("data");
                    JSONArray upperBanner = dataJSONObject.getJSONArray("upperBanner");
                    JSONArray middleBanner = dataJSONObject.getJSONArray("middleBanner");

                    for (int i = 0; i < upperBanner.length(); i++) {
                        BannerEntity bannerEntity = new Gson().fromJson(upperBanner.getJSONObject(i).toString(), BannerEntity.class);
                        tabList.add(bannerEntity);
                        mTablist.add(bannerEntity.getImgUrl());
                    }

                    for (int i = 0; i < middleBanner.length(); i++) {
                        BannerEntity bannerEntity1 = new Gson().fromJson(middleBanner.getJSONObject(i).toString(), BannerEntity.class);
                        entities.add(bannerEntity1);
                        mEntities.add(bannerEntity1.getImgUrl());
                    }
                    banner.setImages(mTablist);//可以选择设置图片网址，或者资源文件，默认用Glide加载
                    bannerActivity.setImages(mEntities);//可以选择设置图片网址，或者资源文件，默认用Glide加载
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });

        JSONObject param_last = new JSONObject();
        try {
            param_last.put("position", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiOkHttp.getClassLabel(getActivity(), param_last, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                if (code == 200) {
                    try {
                        JSONArray jsonArray = data.getJSONArray("data");
                        shopId = jsonArray.getJSONObject(0).getInt("id");
                        mTitle = jsonArray.getJSONObject(0).getString("title");
                        if (shopId != 0 || mTitle != null) {
                            mRlup.setVisibility(View.VISIBLE);
                            mRlvShop.setVisibility(View.VISIBLE);
                            mShopTitle.setText(mTitle);
                            getShopList(shopId);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mRlup.setVisibility(View.GONE);
                    mRlvShop.setVisibility(View.GONE);
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });

        try {
            param.put("position", 2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiOkHttp.getClassLabel(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                mLabelList.clear();
                mTopTabTitle.clear();
                try {
                    JSONArray array = data.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        LabelBean labelBean = new Gson().fromJson(array.getJSONObject(i).toString(), LabelBean.class);
                        mLabelList.add(labelBean);
                        mTopTabTitle.add(labelBean.getTitle());
                        mFragments.add(HomeShopFragment.getInstance(labelBean.getId()));
                    }
                    mViewPager.setAdapter(new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager(), mTopTabTitle, mFragments));
                    mTabLayout.setupWithViewPager(mViewPager);
                    mViewPager.setCurrentItem(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });

    }

    public void getShopList(int type) {
        JSONObject params = new JSONObject();
        try {
            params.put("indexLabelId", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiOkHttp.getShopList(getActivity(), params, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.clear();
                try {
                    JSONArray array = data.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        ShopBean bean = new Gson().fromJson(array.getJSONObject(i).toString(), ShopBean.class);
                        list.add(bean);
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 101) {
                String store_name = data.getStringExtra("store_name");
                mHomeTop.setText(store_name);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
//        banner.isAutoPlay(true);
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.isAutoPlay(false);
        bannerActivity.isAutoPlay(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        String stroeName = SharePreferenceUtils.getString(getActivity(), "store_name");
        mHomeTop.setText(stroeName);
        initData();
        initLabel();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_text: {
                GotoActivity.gotoActiviy(getActivity(), SearchActivity.class);
                break;
            }
            case R.id.home_category: {
                ((MainActivity) this.getActivity()).navigateTo(Constants.NAVIGATE_CATEGORY);
                break;
            }
            case R.id.rl_up: {
                Bundle bundle = new Bundle();
                bundle.putInt("id", shopId);
                bundle.putInt("type", 1);
                bundle.putString("title", mTitle);
                GotoActivity.gotoActiviy(this.getActivity(), RecommendActivity.class, bundle);
                break;
            }
        }
    }

}
